import time
import random
import threading

from utils.utils import nacos_client, DATA_ID, GROUP
from model.db.name_mapping import refresh_name_cache


def publish_update_signal():
    """
    通知所有监听方：name_mapping 数据更新了（实际内容无语义，仅用于触发监听）
    """
    value = f'value-{str(int(time.time()))}-{random.randint(10, 1000)}'
    success = nacos_client.publish_config(DATA_ID, GROUP, value)


    print(f"[Nacos] 发布配置变化: {value}, success={success}")


def start_watch_name_mapping(app):
    """
    启动监听 Nacos 配置变化
    """
    print("[Nacos] 启动 name_mapping 配置监听")

    def _watch_loop():
        last_content = None
        while True:
            try:
                current = nacos_client.get_config(DATA_ID, GROUP)
                if current != last_content:
                    print(f"[Nacos轮询] 检测到配置变化: {current}")
                    last_content = current
                    with app.app_context():
                        refresh_name_cache()
            except Exception as e:
                print(f"[Nacos轮询] 异常: {e}")
            time.sleep(1)  # 合理的轮询间隔

    thread = threading.Thread(target=_watch_loop, args=(), daemon=True)
    # Notice 设置为守护线程 跟随flask项目主线程共同停止
    thread.daemon = True
    thread.start()
